from datetime import datetime

from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import Gathering
from .serializer import GatheringSerializer


# Create your views here.

class GatheringView(ListAPIView):
    """
    获取所有上线活动
    """
    serializer_class = GatheringSerializer
    queryset = Gathering.objects.filter(state=1)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response({'results': serializer.data})


class GatheringInfoView(RetrieveAPIView):
    """
    参加单个活动
    """
    serializer_class = GatheringSerializer
    queryset = Gathering.objects.filter(state=1)


class JoinGatherView(APIView):
    """
    加入或取消活动
    """
    queryset = Gathering.objects.filter(state=1)
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):
        user = request.user
        gathering = Gathering.objects.get(id=pk)
        now_time = datetime.now()
        end_time = gathering.endrolltime.replace(tzinfo=None)

        if end_time < now_time:
            return Response({'message': '报名已截止，请参加其他活动', 'success': False}, status=400)
        else:
            if user in gathering.users.all():
                gathering.users.remove(user)
                gathering.save()
                return Response({'message': '取消活动报名成功', 'success': True})
            else:
                gathering.users.add(user)
                gathering.save()
                return Response({'message': '活动报名成功', 'success': True})
